namespace DependencyAnalysis.Algorithms.SubstringDetection
{
    public class Edge
    {
        public int BeginIndex { get; private set; }
        public int EndIndex { get; set; }
        public Node StartNode { get; set; }
        public Node EndNode { get; private set; }

        // each time edge is created, a new end node is created
        public Edge(int beginIndex, int endIndex, Node startNode)
        {
            BeginIndex = beginIndex;
            EndIndex = endIndex;
            StartNode = startNode;
            EndNode = new Node(startNode.Tree, null);
        }

        public Node SplitEdge(Suffix suffix)
        {
            Remove();
            Edge newEdge = new Edge(BeginIndex, BeginIndex + suffix.GetSpan(), suffix.OriginNode);
            newEdge.Insert();
            newEdge.EndNode.SuffixNode = suffix.OriginNode;
            BeginIndex += suffix.GetSpan() + 1;
            StartNode = newEdge.EndNode;
            Insert();
            return newEdge.EndNode;
        }

        public void Insert()
        {
            StartNode.AddEdge(BeginIndex, this);
        }

        public void Remove()
        {
            StartNode.RemoveEdge(BeginIndex);
        }

        public int GetSpan()
        {
            return EndIndex - BeginIndex;
        }
    }
}